package com.css.crm.utility;

import java.math.BigDecimal;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * validate some field
 * 
 * @author AIS
 * 
 */
public class ValidateUtil {

	private static final String EMAIL_FMT = "^([a-z0-9A-Z]+[\\.\\_\\-\\*\\^]*)+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
	
	// Number format
	private static final String NUMBER_FMT = "[-+]?\\d+(\\.\\d+)?";

	/**
	 * validate null
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateEmpty(String value) {
		if (value == null || "".equals(value) || "".equals(value.trim())) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * validate value by pattern
	 * 
	 * @param value
	 * @param pattern
	 * @return
	 */
	public static boolean validatePattern(String value, String pattern) {
		Pattern regex = Pattern.compile(pattern);
		Matcher matcher = regex.matcher(value);
		boolean isMatched = matcher.matches();
		return isMatched;
	}

	/**
	 * check email
	 * 
	 * @param email
	 * @return
	 */
	public static boolean validateEmail(String email) {
		return validatePattern(email, EMAIL_FMT);
	}	

	/**
	 * validate number
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateNumber(String value) {
		return validatePattern(value, NUMBER_FMT);
	}

	public static boolean validateLeastOneNotEmpty(String... strArray) {
		boolean flag = false;
		if (strArray != null) {
			for (String str : strArray) {
				if (validateEmpty(str)) {
					flag = true;
					break;
				}
			}
		}

		return flag;
	}

	public static boolean isAllEmpty(Object... objArray) {
		boolean flag = true;
		if (objArray != null) {
			for (Object obj : objArray) {
				if (obj instanceof String) {
					if (validateEmpty((String) obj)) {
						flag = false;
						break;
					}
				} else if (obj instanceof Number || obj instanceof Boolean) {
					if (obj != null) {
						flag = false;
						break;
					}
				} else {
					if (obj != null) {
						flag = false;
						break;
					}
				}

			}
		}

		return flag;
	}

	public static boolean checkRecordIntact(Object... objArray) {
		boolean flag = true;
		if (objArray != null) {
			for (Object obj : objArray) {
				if (obj instanceof String) {
					if (!validateEmpty((String) obj)) {
						flag = false;
						break;
					}
				} else if (obj instanceof BigDecimal) {
					if (obj == null || ((BigDecimal) obj).intValue() == 0) {
						flag = false;
						break;
					}
				} else if (obj instanceof Number || obj instanceof Boolean) {
					if (obj == null) {
						flag = false;
						break;
					}
				} else if (obj instanceof List) {
					List list = (List) obj;
					if (list.size() < 1) {
						flag = false;
						break;
					}
				} else {
					if (obj == null) {
						flag = false;
						break;
					}
				}
			}
		}

		return flag;
	}

}
